package com.zy.imagineCommunity.controller;

import com.alibaba.fastjson.JSONObject;
import com.zy.imagineCommunity.entity.User;
import com.zy.imagineCommunity.service.UserSerivce;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@Controller
public class LoginController {

    public static Map<Integer, String> map = new HashMap<Integer, String>();

    @Autowired
    private UserSerivce userSerivce;

    @RequestMapping(path = "/login", method = RequestMethod.GET)
    public String getLogin() {
        return "/login";
    }

    @ResponseBody
    @RequestMapping(path = "/login", method = RequestMethod.POST)
    public JSONObject Login(String username, String password, HttpSession session) {

        JSONObject jsonObject = new JSONObject();

        //对密码进行 md5 加密
        String md5Password = DigestUtils.md5DigestAsHex(password.getBytes());

        User user = userSerivce.queryUserByUsernameAndPassword(username, md5Password);

        if (user == null) {
            jsonObject.put("user", "no");
            jsonObject.put("msg", "账号不存在或密码错误!");
            return jsonObject;
        }

        if (user.getUserStatus() == 0) {
            jsonObject.put("user", "no");
            jsonObject.put("msg", "账号未激活!");
            return jsonObject;
        }

        if (user.getUserStatus() == 2) {
            jsonObject.put("user", "no");
            jsonObject.put("msg", "账号被禁用!");
            return jsonObject;
        }

        for (Map.Entry<Integer, String> entry : map.entrySet()) {

            int id = entry.getKey();

            if (id == user.getId()) {

                jsonObject.put("user", "no");

                jsonObject.put("msg", "此账号已被登录!");

                return jsonObject;

            }

        }

        if (user != null) {

            //设置session超时时长
            session.setMaxInactiveInterval(60 * 60 * 12);
            //用户信息保存在session域中
            session.setAttribute("user", user);

            map.put(user.getId(), user.getUsername());

            jsonObject.put("user", "yes");

            return jsonObject;
        }

        return jsonObject;
    }

    /**
     * 退出社区登录状态
     *
     * @return
     */
    @GetMapping("/outLogin")
    public String outLogin(int id, HttpSession session) {

        session.removeAttribute("user");

        User user = userSerivce.queryUserByUserId(id);

        Iterator<Integer> iterator = map.keySet().iterator();

        while (iterator.hasNext()) {

            int keyId = iterator.next();

            if (keyId == user.getId()) {

                iterator.remove();

            }

        }

        return "/login";
    }

    /**
     * 跳转到后台登录
     *
     * @return
     */
    @GetMapping("/AdminLogin")
    public String getAdminLogin() {
        return "/AdminLogin";
    }

    /**
     * 管理员登录
     *
     * @param username
     * @param password
     * @param req
     * @return
     */
    @ResponseBody
    @PostMapping("/AdminLogin")
    public JSONObject AdminLogin(String username, String password, HttpServletRequest req) {

        JSONObject jsonObject = new JSONObject();

        //对密码进行 md5 加密
        String md5Password = DigestUtils.md5DigestAsHex(password.getBytes());

        User user = userSerivce.queryUserByUsernameAndPassword(username, md5Password);

        if (user == null) {
            jsonObject.put("user", "no");
            jsonObject.put("msg", "账号不存在或密码错误!");
            return jsonObject;
        }

        if (user.getUserStatus() == 0) {
            jsonObject.put("user", "no");
            jsonObject.put("msg", "账号未激活!");
            return jsonObject;
        }
        if (user.getUserStatus() == 1) {
            jsonObject.put("user", "no");
            jsonObject.put("msg", "此用户非管理员!");
            return jsonObject;
        }
        if (user.getUserStatus() == 2) {
            jsonObject.put("user", "no");
            jsonObject.put("msg", "账号被禁用!");
            return jsonObject;
        }

        for (Map.Entry<Integer, String> entry : map.entrySet()) {

            int id = entry.getKey();

            if (id == user.getId()) {

                jsonObject.put("user", "no");

                jsonObject.put("msg", "账号已被登录!");

                return jsonObject;

            }

        }

        if (user.getUserStatus() == 3) {
            //获取session
            HttpSession session = req.getSession();
            //设置session超时时长
            session.setMaxInactiveInterval(60 * 60 * 12);
            //用户信息保存在session域中
            session.setAttribute("adminUser", user);

            map.put(user.getId(), user.getUsername());

            jsonObject.put("user", "yes");

            return jsonObject;
        }
        if (user.getUserStatus() == 4) {
            //获取session
            HttpSession session = req.getSession();
            //设置session超时时长
            session.setMaxInactiveInterval(60 * 60 * 12);
            //用户信息保存在session域中
            session.setAttribute("adminUser", user);

            map.put(user.getId(), user.getUsername());

            jsonObject.put("user", "Java");

            return jsonObject;
        }
        if (user.getUserStatus() == 5) {
            //获取session
            HttpSession session = req.getSession();
            //设置session超时时长
            session.setMaxInactiveInterval(60 * 60 * 12);
            //用户信息保存在session域中
            session.setAttribute("adminUser", user);

            map.put(user.getId(), user.getUsername());

            jsonObject.put("user", "C++");

            return jsonObject;
        }
        if (user.getUserStatus() == 6) {
            //获取session
            HttpSession session = req.getSession();
            //设置session超时时长
            session.setMaxInactiveInterval(60 * 60 * 12);
            //用户信息保存在session域中
            session.setAttribute("adminUser", user);

            map.put(user.getId(), user.getUsername());

            jsonObject.put("user", "Python");

            return jsonObject;
        }
        if (user.getUserStatus() == 7) {
            //获取session
            HttpSession session = req.getSession();
            //设置session超时时长
            session.setMaxInactiveInterval(60 * 60 * 12);
            //用户信息保存在session域中
            session.setAttribute("adminUser", user);

            map.put(user.getId(), user.getUsername());

            jsonObject.put("user", "JavaScript");

            return jsonObject;
        }
        if (user.getUserStatus() == 8) {
            //获取session
            HttpSession session = req.getSession();
            //设置session超时时长
            session.setMaxInactiveInterval(60 * 60 * 12);
            //用户信息保存在session域中
            session.setAttribute("adminUser", user);

            map.put(user.getId(), user.getUsername());

            jsonObject.put("user", "c");

            return jsonObject;
        }
        if (user.getUserStatus() == 9) {
            //获取session
            HttpSession session = req.getSession();
            //设置session超时时长
            session.setMaxInactiveInterval(60 * 60 * 12);
            //用户信息保存在session域中
            session.setAttribute("adminUser", user);

            map.put(user.getId(), user.getUsername());

            jsonObject.put("user", "yun");

            return jsonObject;
        }

        return jsonObject;
    }

    /**
     * 退出后台登录状态
     * 在遍历Map时是不可以删除key-value映射的，如果根据key删除,会报错：并发修改异常，意思就是正在对map进行遍历的过程中不能删除map中的key-value
     * 我们可以使用迭代器删除,可以根据key删除map中key-value映射
     *
     * @return
     */
    @GetMapping("/outAdminLogin")
    public String outAdminLogin(int id, HttpSession session) {

        session.removeAttribute("adminUser");

        User user = userSerivce.queryUserByUserId(id);

        Iterator<Integer> iterator = map.keySet().iterator();

        while (iterator.hasNext()) {

            int keyId = iterator.next();

            if (keyId == user.getId()) {

                iterator.remove();

            }

        }

        return "/AdminLogin";
    }

}
